#include<vector>
#include<unordered_set>
using namespace std;
class Solution {
    //0:
    //1: visited;
    //2: unsafe;
    //3: safe;
    bool dfs(const vector<vector<int>>& graph, int idx, vector<int>&flags) {
        if (flags[idx] == 3)
            return true;
        if (flags[idx] == 1)
            flags[idx] = 2;
        if (flags[idx] == 2)
            return false;
            
        flags[idx] = 1;
        for (int i = 0; i < graph[idx].size(); ++i) {
            if (!dfs(graph, graph[idx][i], flags)) {
                flags[idx] = 2;
                return false;
            }
        }
        flags[idx] = 3;
        return true;
    }

public:
    vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
        int N = graph.size();
        vector<int>flags(N);
        vector<int>res;
        for (int i = 0; i < N; ++i) {
            if (dfs(graph, i, flags)) {
                res.push_back(i);
            }
        }
        return res;
    }
};